package com.jieshuibao.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.jieshuibao.common.config.Global;
import com.jieshuibao.common.po.PageRes;
import com.jieshuibao.common.res.BaseRes;
import com.jieshuibao.model.db.User;
import com.jieshuibao.model.db.Video;
import com.jieshuibao.model.db.VideoBuyHistory;
import com.jieshuibao.model.db.VideoBuyHistoryExample;
import com.jieshuibao.model.db.VideoCard;
import com.jieshuibao.model.db.VideoExample;
import com.jieshuibao.model.db.VideoExample.Criteria;
import com.jieshuibao.model.domain.CookieUser;
import com.jieshuibao.model.domain.VideoReq;
import com.jieshuibao.service.RedisService;
import com.jieshuibao.service.UserService;
import com.jieshuibao.service.VideoBuyHistoryService;
import com.jieshuibao.service.VideoCardService;
import com.jieshuibao.service.VideoService;
import com.jieshuibao.service.WeiXinPayService;
import com.jieshuibao.util.PayTypeUtil;
import com.jieshuibao.util.StringUtils;
import com.jieshuibao.util.UUIDGenerator;
import com.jieshuibao.wx.po.WxAppPayReq;
import com.jieshuibao.wx.po.WxAppPayRes;
import com.jieshuibao.wx.util.PayCommonUtil;

@Controller
@RequestMapping(value = "/video")
public class VideoPersonalController {
	@Resource
	private VideoService videoService;
	@Resource
	private RedisService redisService;
	@Resource
	private VideoBuyHistoryService videoBuyHistoryService;
	@Resource
	private UserService userService;
	@Resource
	private WeiXinPayService weiXinPayService;
	@Resource
	private VideoCardService videoCardService;

	/**
	 * C版APP视频列表
	 * 
	 * @param request
	 * @param req
	 * @return
	 */
	@RequestMapping(value = "/list", method = RequestMethod.POST)
	@ResponseBody
	public Object list(HttpServletRequest request, @RequestBody VideoReq req) {
		PageRes res = new PageRes();
		String cookieId = request.getHeader("cookieId");
		if (StringUtils.isEmpty(cookieId)) {
			res.setCode("2");
			res.setDes("重新登录!");
			return res;
		}
		CookieUser cookieUser = redisService.getObejct(cookieId, CookieUser.class);
		if (cookieUser == null) {
			res.setCode(Global.NOTLOGIN);
			res.setDes("重新登录!");
			return res;
		}
		String userid = cookieUser.getPhoneNumber();
		String type = req.getType();
		if (StringUtils.isEmpty(type)) {
			res.setCode("0");
			res.setDes("系统繁忙!");
			return res;
		}
		int sinceId = req.getSinceId();
		int maxId = req.getMaxId();
		if (sinceId <= 0) {
			sinceId = 1;
		}
		if (maxId <= 0 || maxId < sinceId) {
			maxId = sinceId;
		}
		VideoExample videoExample = new VideoExample();
		Criteria criteria = videoExample.createCriteria();
		criteria.andTypeEqualTo(type);
		criteria.andDelFlagEqualTo(Global.SHOW);
		videoExample.setPageIndex(sinceId - 1);
		videoExample.setPageSize(maxId - sinceId + 1);
		videoExample.setOrderByClause("sort ");
		List<Video> videos = videoService.getPageVideo(videoExample);
		for (Video video : videos) {
			video.setVid("");
		}
		Map<String,Object> map = new HashMap<String,Object>();
		User user = userService.getUserByPhoneNumber(userid);
		Date videoVipInvalidTime = user.getVideoVipInvalidTime();
		if(userService.isVideoVip(userid)){
			res.setCode("1");
			map.put("vip", "0");
			map.put("videoVipInvalidTime", videoVipInvalidTime.getTime());
			map.put("videos", videos);
			res.setData(map);
			res.setTotalCount(videos.size());
			return res;
		}
		res.setCode("1");
		map.put("vip", "1");
		map.put("videos", videos);
		res.setData(map);
		res.setTotalCount(videos.size());
		return res;
	}

	@RequestMapping(value = "/buylist", method = RequestMethod.POST)
	@ResponseBody
	public Object buylist(HttpServletRequest request, @RequestBody VideoReq req) {
		PageRes res = new PageRes();
		//String cookieId = request.getHeader("cookieId");
		//if (StringUtils.isEmpty(cookieId)) {
			//res.setCode("2");
			//res.setDes("重新登录!");
			//return res;
		//}
		//CookieUser cookieUser = redisService.getObejct(cookieId, CookieUser.class);
		CookieUser cookieUser = (CookieUser)request.getAttribute("cookieUser");
		System.out.println("cookieUser: "+cookieUser);
		if (cookieUser == null) {
			res.setCode(Global.NOTLOGIN);
			res.setDes("重新登录!");
			return res;
		}
		String userid = cookieUser.getPhoneNumber();
	
		VideoBuyHistoryExample example = new VideoBuyHistoryExample();
		com.jieshuibao.model.db.VideoBuyHistoryExample.Criteria createCriteria = example.createCriteria();
		createCriteria.andUserIdEqualTo(userid);
		createCriteria.andStatusEqualTo(PayCommonUtil.PAYSUCCESS_STATUS);
		createCriteria.andGoodsTypeEqualTo(PayTypeUtil.GOODSTYPE_VIDEO_SINGLE);
		int sinceId = req.getSinceId();
		int maxId = req.getMaxId();
		if (sinceId <= 0) {
			sinceId = 1;
		}
		if (maxId <= 0 || maxId < sinceId) {
			maxId = sinceId;
		}
		example.setPageIndex(sinceId - 1);
		example.setPageSize(maxId - sinceId + 1);
		example.setOrderByClause("createDate DESC");
		List<VideoBuyHistory> buyvideo = videoBuyHistoryService.getPageVideoBuyHistory(example);
		List<Video> list = new ArrayList<Video>();
		for (VideoBuyHistory videoBuyHistory : buyvideo) {
			String goodsId = videoBuyHistory.getGoodsId();
			Video videoById = videoService.getVideoById(goodsId);
			list.add(videoById);
		}
		res.setCode("1");
		res.setData(list);
		res.setTotalCount(list.size());
		return res;
	}

	/**
	 * C版APP视频授权（是否返回vid）
	 * 
	 * @param request
	 * @param req
	 * @return
	 */
	@RequestMapping(value = "/vid", method = RequestMethod.POST)
	@ResponseBody
	public Object vid(HttpServletRequest request, @RequestBody VideoReq req) {
		BaseRes<Object> res = new BaseRes<Object>();
		Map<String, String> map = new HashMap<String, String>();
		CookieUser cookieUser = (CookieUser)request.getAttribute("cookieUser");
		String userid = cookieUser.getPhoneNumber();
		String id = req.getId();
		// TODO 判断该用户是否购买该视频
		Video videoById = videoService.getVideoById(id);
		if (null == videoById) {
			res.setCode(BaseRes.ERRORPARAM_CODE);
			res.setDes(BaseRes.ERRORPARAM_DES);
			return res;
		}
		Double price = videoById.getPrice();
		if (price==null||price==0) {
			map.put("vid", videoById.getVid());
			res.setCode(BaseRes.SUCCESS_CODE);
			res.setData(map);
			return res;
		}
		boolean buyVideo = videoService.isBuyVideo(userid, id);
		if(buyVideo || userService.isVideoVip(userid)){//已购买该视频 或者 购买了视频卡
			map.put("vid", videoById.getVid());
			res.setCode(BaseRes.SUCCESS_CODE);
			res.setData(map);
			return res;
		}
		map.put("vid", "");//未购买
		res.setCode(BaseRes.SUCCESS_CODE);
		res.setData(map);
		return res;
	}
	/**
	 * 购买单个视频
	 * @param request
	 * @param req
	 * @return
	 */
	@RequestMapping(value = "/buysingle", method = RequestMethod.POST)
	@ResponseBody
	public Object buysingle(HttpServletRequest request, @RequestBody VideoReq req) {
		BaseRes<Object> res = new BaseRes<Object>();
		String cookieId = request.getHeader("cookieId");
		if (StringUtils.isEmpty(cookieId)) {
			res.setCode("2");
			res.setDes("重新登录!");
			return res;
		}
		CookieUser cookieUser = redisService.getObejct(cookieId, CookieUser.class);
		if (cookieUser == null) {
			res.setCode(Global.NOTLOGIN);
			res.setDes("重新登录!");
			return res;
		}
		String userid = cookieUser.getPhoneNumber();
		String id = req.getId();
		Video videoById = videoService.getVideoById(id);
		if (null == videoById) {
			res.setCode("0");
			res.setDes("系统繁忙!");
			return res;
		}
		String payType = req.getPayType();
		if(StringUtils.isEmpty(payType)){
			res.setCode("0");
			res.setDes("支付方式不能为空");
			return res;
		}
		VideoBuyHistoryExample example = new VideoBuyHistoryExample();
		com.jieshuibao.model.db.VideoBuyHistoryExample.Criteria criteria = example.createCriteria();
		criteria.andUserIdEqualTo(userid);
		criteria.andGoodsIdEqualTo(id);
		criteria.andStatusEqualTo(PayCommonUtil.PAYSUCCESS_STATUS);
		List<VideoBuyHistory> videos = videoBuyHistoryService.selectByExample(example );
		if(null != videos && videos.size()>0){//已购买该视频
			res.setCode("0");
			res.setDes("该视频已经购买过");
			return res;
		}
		Double price = videoById.getPrice();
		VideoBuyHistory videoBuyHistory = new VideoBuyHistory();
		videoBuyHistory.setCreateDate(new Date());
		videoBuyHistory.setGoodsId(id);
		videoBuyHistory.setGoodsType(PayTypeUtil.GOODSTYPE_VIDEO_SINGLE);
		String uuid = UUIDGenerator.getUUID();
		videoBuyHistory.setId(uuid);
		videoBuyHistory.setPrice(price);
		videoBuyHistory.setStatus(PayCommonUtil.PAYPENDING_STATUS);
		videoBuyHistory.setUserId(userid);
		if(PayTypeUtil.PAYTYPE_BALANCE.equals(payType)){//余额支付
			User user = userService.getUserByPhoneNumber(userid);
			Double balance = user.getBalance();
			if(balance<price){
				res.setCode("0");
				res.setDes("余额不足");
				return res;
			}
			Double money = balance - price;
			videoBuyHistory.setPayType(PayTypeUtil.PAYTYPE_BALANCE);
			try {
				videoBuyHistoryService.addVideoBuyHistory(videoBuyHistory );
				videoBuyHistoryService.updateBalanceBuyVideo(userid,money,uuid);
				res.setCode("1");
				res.setDes("支付成功");
				return res;
			} catch (Exception e) {
				e.printStackTrace();
				res.setCode("0");
				res.setDes("系统繁忙");
				return res;
			}
		}else if(PayTypeUtil.PAYTYPE_WEIXIN.equals(payType)){//微信支付
			videoBuyHistory.setPayType(PayTypeUtil.PAYTYPE_WEIXIN);
			videoBuyHistoryService.addVideoBuyHistory(videoBuyHistory );
			WxAppPayReq wxAppPayReq = new WxAppPayReq();
			wxAppPayReq.setAmount(1);
			wxAppPayReq.setUnitPrice(price);
			wxAppPayReq.setPhone(userid);
			wxAppPayReq.setProductId(uuid);
			wxAppPayReq.setProductName("单个视频");
			wxAppPayReq.setProductType(PayTypeUtil.GOODSTYPE_VIDEO_SINGLE);
			WxAppPayRes wxAppPayRes = (WxAppPayRes)weiXinPayService.appPay(wxAppPayReq , request);
			return wxAppPayRes;
		}else{
			res.setCode("0");
			res.setDes("支付方式错误");
			return res;
		}
	}
	
	/**
	 * 购买视频卡
	 * @param request
	 * @param req
	 * @return
	 */
	@RequestMapping(value = "/buycard", method = RequestMethod.POST)
	@ResponseBody
	public Object buycard(HttpServletRequest request, @RequestBody VideoReq req) {
		BaseRes<Object> res = new BaseRes<Object>();
		String cookieId = request.getHeader("cookieId");
		if (StringUtils.isEmpty(cookieId)) {
			res.setCode("2");
			res.setDes("重新登录!");
			return res;
		}
		CookieUser cookieUser = redisService.getObejct(cookieId, CookieUser.class);
		if (cookieUser == null) {
			res.setCode(Global.NOTLOGIN);
			res.setDes("重新登录!");
			return res;
		}
		String userid = cookieUser.getPhoneNumber();
		String id = req.getId();
		VideoCard videoCardByUuid = videoCardService.getVideoCardByUuid(id);
		if(null == videoCardByUuid){
			res.setCode("0");
			res.setDes("该会员卡不存在!");
			return res;
		}
		String payType = req.getPayType();
		if(StringUtils.isEmpty(payType)){
			res.setCode("0");
			res.setDes("支付方式不能为空");
			return res;
		}
		Double price = videoCardByUuid.getPrice().doubleValue();
		VideoBuyHistory videoBuyHistory = new VideoBuyHistory();
		videoBuyHistory.setCreateDate(new Date());
		videoBuyHistory.setGoodsId(id);
		videoBuyHistory.setGoodsType(PayTypeUtil.GOODSTYPE_VIDEO_CARD);
		String uuid = UUIDGenerator.getUUID();
		videoBuyHistory.setId(uuid);
		videoBuyHistory.setPrice(price);
		videoBuyHistory.setStatus(PayCommonUtil.PAYPENDING_STATUS);
		videoBuyHistory.setUserId(userid);
		videoBuyHistory.setValidperiod(videoCardByUuid.getVideoDays());
		if(PayTypeUtil.PAYTYPE_BALANCE.equals(payType)){//余额支付
			User user = userService.getUserByPhoneNumber(userid);
			Double balance = user.getBalance();
			if(balance<price){
				res.setCode("0");
				res.setDes("余额不足");
				return res;
			}
			Double money = balance - price;
			videoBuyHistory.setPayType(PayTypeUtil.PAYTYPE_BALANCE);
			try {
				videoBuyHistoryService.addVideoBuyHistory(videoBuyHistory );
				videoBuyHistoryService.updateBalanceBuyCard(userid, money, uuid);
				res.setCode("1");
				res.setDes("支付成功");
				return res;
			} catch (Exception e) {
				e.printStackTrace();
				res.setCode("0");
				res.setDes("系统繁忙");
				return res;
			}
		}else if(PayTypeUtil.PAYTYPE_WEIXIN.equals(payType)){//微信支付
			videoBuyHistory.setPayType(PayTypeUtil.PAYTYPE_WEIXIN);
			videoBuyHistoryService.addVideoBuyHistory(videoBuyHistory );
			WxAppPayReq wxAppPayReq = new WxAppPayReq();
			wxAppPayReq.setAmount(1);
			wxAppPayReq.setUnitPrice(price);
			wxAppPayReq.setPhone(userid);
			wxAppPayReq.setProductId(uuid);
			wxAppPayReq.setProductName("视频卡");
			wxAppPayReq.setProductType(PayTypeUtil.GOODSTYPE_VIDEO_CARD);
			WxAppPayRes wxAppPayRes = (WxAppPayRes)weiXinPayService.appPay(wxAppPayReq , request);
			return wxAppPayRes;
		}else{
			res.setCode("0");
			res.setDes("支付方式错误");
			return res;
		}
	}
}
